package com.pdsu.graduation_design.views;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.pdsu.graduation_design.MainActivity;
import com.pdsu.graduation_design.adapter.MyCommodityUpSpinnerAdapter_CommodityType;
import com.pdsu.graduation_design.adapter.MyCommodityUpSpinnerAdapter_Type;
import com.pdsu.graduation_design.R;
import com.pdsu.graduation_design.domain.Commodity;
import com.pdsu.graduation_design.domain.CommodityType;
import com.pdsu.graduation_design.domain.Type;
import com.pdsu.graduation_design.utils.JsonUtil;
import com.pdsu.graduation_design.utils.Result;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

public class My_Up_Commodity_Activity extends AppCompatActivity {
    private static final int REQUEST_CODE_WRITE_EXTERNAL_STORAGE = 1;
    private static final int REQUEST_CODE_READ_EXTERNAL_STORAGE = 1;
    private int ctid_p=-1;
    private Context context;
    private Activity this_c;
    private boolean isChecked=false;
    private EditText cname,cprice,cmessage,cnumber;
    //初始化
    private Spinner type_spin,ctype_spin;
    private ImageView imageView;
    private Button submit;
    private List<Type> typeList_p;
    private List<CommodityType> commodityTypeList_p;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_up_commodity);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_WRITE_EXTERNAL_STORAGE);
            }
        }

        init();
        bind();
    }

    void check(){
        if (cname.getText().toString().length()==0||cnumber.getText().length()==0||cmessage.getText().length()==0||cprice.getText().length()==0){
            isChecked=false;
        }
    }
    void bind(){
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                check();
                if (isChecked){
                    Bitmap bitmap=  ((BitmapDrawable) imageView.getDrawable()).getBitmap();
                    String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/image.jpg";
                    File file = new File(filePath);
                    //动态获取权限
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                            ActivityCompat.requestPermissions(this_c, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE_READ_EXTERNAL_STORAGE);
                            ActivityCompat.requestPermissions(this_c, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_WRITE_EXTERNAL_STORAGE);
                        } else {
                            if (!file.exists()) {
                                try {
                                    file.getParentFile().mkdirs();
                                    file.createNewFile();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                            FileOutputStream fos = null;
                            try {
                                fos = new FileOutputStream(file);
                                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                                fos.flush();
                            } catch (Exception e) {
                                e.printStackTrace();
                            } finally {
                                if (fos != null) {
                                    try {
                                        fos.close();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }

                            /**
                             *
                             */
                        }
                    }
                    //添加url
                    RequestParams params = new RequestParams(MainActivity.URL+"/commodity/uploadImage");
                    params.setMultipart(true);
                    Commodity commodity = new Commodity();
                    commodity.setCmessage(cmessage.getText().toString());
                    commodity.setCname(cname.getText().toString());
                    commodity.setPrice(Double.valueOf(cprice.getText().toString()));
                    commodity.setCnumber(Integer.valueOf(cnumber.getText().toString()));
                    commodity.setUsername(MainActivity.user_admin.getUsername());
                    commodity.setUid(MainActivity.user_admin.getUid());
                    commodity.setCtid(ctid_p);
                    String Json_t=null;
                    try {
                       Json_t = JsonUtil.ObjToJson(commodity);
                    } catch (JsonProcessingException e) {
                        e.printStackTrace();
                    }
                    params.addParameter("commodity",Json_t);
                    params.addBodyParameter("file", file, "multipart/form-data");
                    x.http().post(params, new Callback.CommonCallback<String>() {
                        @Override
                        public void onSuccess(String result) {
                            Toast.makeText(context, "ok", Toast.LENGTH_SHORT).show();
                            finish();
                        }
                        @Override
                        public void onError(Throwable ex, boolean isOnCallback) {
                        }
                        @Override
                        public void onCancelled(CancelledException cex) {
                        }
                        @Override
                        public void onFinished() {
                        }
                    });
                }else {
                    Toast.makeText(context, "请完善商品信息", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    void init (){
        context=getApplicationContext();
        this_c=this;
        imageView=findViewById(R.id.imageView);
        cname=findViewById(R.id.nameEditText);
        cprice=findViewById(R.id.priceEditText);
        cmessage=findViewById(R.id.descriptionEditText);
        cnumber=findViewById(R.id.numberEditText);
        submit=findViewById(R.id.uploadButton);
        type_spin=findViewById(R.id.categorySpinner);
        ctype_spin=findViewById(R.id.categorySpinner_ctid);


        RequestParams params=new RequestParams(MainActivity.URL+"/commodity/getAllType");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    Result r= JsonUtil.JsonToObj(result,Result.class);
                    if (r.getCode().equals("200")){
                        List<Type> types=JsonUtil.json2list(r.getData().toString(),Type.class);
                        setData(types);

                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }
            @Override
            public void onCancelled(CancelledException cex) {
            }
            @Override
            public void onFinished() {
            }
        });
    }
    void setData(List<Type> types){
        type_spin.setAdapter(new MyCommodityUpSpinnerAdapter_Type(context,types));
        type_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position>=0) {

                    setCType(types.get(position).getTid());
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        setCType(types.get(0).getTid());
    }
    void setCType(int tid){

        RequestParams requestParams = new RequestParams(MainActivity.URL+"/commodity/getCommodityTypeByTID");
        requestParams.addParameter("tid",tid);
        x.http().post(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    Result r= JsonUtil.JsonToObj(result,Result.class);
                    if (r.getCode().equals("200")){
                        List<CommodityType> commodityTypes= JsonUtil.json2list(r.getData().toString(),CommodityType.class);
                        ctype_spin.setAdapter(new MyCommodityUpSpinnerAdapter_CommodityType(context,commodityTypes));
                        ctype_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                ctid_p= commodityTypes.get(position).getCtid();
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {

                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            Uri imageUri = data.getData();
            System.out.println(imageUri+"uri");
            imageView.setImageURI(imageUri);
            isChecked=true;
        }
    }
    public void selectImage(View view) {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, 1);
    }
}